﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Globalization;
using SilverlightSdms.VisitsService;

namespace SilverlightSdms.Views
{
    public partial class FiscalServicesManager : Page
    {

        private List<ExtendedVisitInfo> m_searchVisitResult;

        private double m_hoursCompleted = 0;
        private double m_hoursRemain = 0;
        private int m_selectedMonth = 0;
        private int m_searchedUserID = -1;

        public FiscalServicesManager()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void FSM_Loaded(object sender, RoutedEventArgs e)
        {
            this.comboBoxMonths.ItemsSource = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
            this.comboBoxMonths.SelectedItem = (CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[DateTime.Today.Month - 1]);
            setAllSalaryButtonsEnableState(false);

            // Do not load your data at design time.
            // if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            // {
            // 	//Load your data here and assign the result to the CollectionViewSource.
            // 	System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["Resource Key for CollectionViewSource"];
            // 	myCollectionViewSource.Source = your data
            // }
        }

        private void buttonSearchNow_Click(object sender, RoutedEventArgs e)
        {
            var visits = new VisitsService.VisitsServiceClient();
            m_selectedMonth = comboBoxMonths.SelectedIndex + 1;

            visits.GetVisitsForMonthCompleted += (s, ea) =>
            {
                this.visits1.dataGridMonthlyVisits.AutoGenerateColumns = true;
                this.visits1.dataGridMonthlyVisits.ItemsSource = ea.Result;
                m_searchVisitResult = ea.Result.ToList<ExtendedVisitInfo>();
                if (m_searchVisitResult.Count > 0)
                {
                    m_searchedUserID = m_searchVisitResult[0].UserId;
                    this.textBoxDisplayName.Text = m_searchVisitResult[0].DisplayName;
                    setVisitDutyStatus();
                    setAllSalaryButtonsEnableState(true);
                }
                else
                {
                    this.textBoxDisplayName.Text = "NOT FOUND";
                    this.textBoxCompletedHours.Text = textBoxHoursRemain.Text = string.Empty;
                    setAllSalaryButtonsEnableState(false);
                }
            };

            int userId = -1; // there is no such ID
            int.TryParse(this.textBoxID.Text, out userId);
            visits.GetVisitsForMonthAsync(userId, this.textBoxUserName.Text, m_selectedMonth);
        }

        private void setVisitDutyStatus()
        {
            m_hoursCompleted = m_hoursRemain = 0;
            foreach (ExtendedVisitInfo visit in m_searchVisitResult)
            {
                if (visit.IsDone)
                {
                    m_hoursCompleted += (visit.EndTime.TimeOfDay.TotalHours - visit.StartTime.TimeOfDay.TotalHours);
                }
                else
                {
                    m_hoursRemain += (visit.EndTime.TimeOfDay.TotalHours - visit.StartTime.TimeOfDay.TotalHours);
                }
            }

            this.textBoxCompletedHours.Text = m_hoursCompleted.ToString();
            this.textBoxHoursRemain.Text = m_hoursRemain.ToString();
        }

        private void textBoxID_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxID.Text))
            {
                this.textBoxUserName.IsEnabled = false;
                this.buttonSearchNow.IsEnabled = true;
            }
            else
            {
                this.textBoxUserName.IsEnabled = true;
                this.buttonSearchNow.IsEnabled = false;
            }
        }

        private void textBoxUserName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(textBoxUserName.Text))
            {
                this.textBoxID.IsEnabled = false;
                this.buttonSearchNow.IsEnabled = true;
            }
            else
            {
                this.textBoxID.IsEnabled = true;
                this.buttonSearchNow.IsEnabled = false;
            }
        }

        private void buttonApproveSalary_Click(object sender, RoutedEventArgs e)
        {
            var paychecks = new PaychecksService.PaychecksServiceClient();

            paychecks.AddPaycheckCompleted += (s, ea) =>
            {
                // onComplete check errors!!!
                // ea.Error
                if (ea.Error == null)
                {
                    string resultMessage = ea.Result ? "Paycheck already approved" : "Paycheck added succesfully";
                    MessageBox.Show(resultMessage);
                }
                else
                {
                    MessageBox.Show("Failed adding paycheck: " + ea.Error.Message);
                }
            };

            paychecks.AddPaycheckAsync(m_searchedUserID, m_selectedMonth, m_hoursCompleted);
        }

        private void setAllSalaryButtonsEnableState(bool isEnabled)
        {
            buttonAddBonus.IsEnabled = buttonFineSalary.IsEnabled = buttonApproveSalary.IsEnabled = isEnabled;
        }

        private void buttonAddBonus_Click(object sender, RoutedEventArgs e)
        {
            var paychecks = new PaychecksService.PaychecksServiceClient();

            paychecks.AddBonusCompleted += (s, ea) =>
            {
                if (ea.Error == null)
                {
                    string resultMessage = ea.Result ? "Bonus added succesfully" : "Paycheck wasn't approved yet";
                    MessageBox.Show(resultMessage);
                }
                else
                {
                    MessageBox.Show("Failed adding bonus: " + ea.Error.Message);
                }
            };

            int bonus = 0;
            int.TryParse(this.textBoxBonus.Text, out bonus);
            if (bonus > 0)
            {
                paychecks.AddBonusAsync(m_searchedUserID, m_selectedMonth, bonus);
            }
            else
            {
                MessageBox.Show("Bonus Must be integer bigger then 0");
            }
        }

        private void buttonFineSalary_Click(object sender, RoutedEventArgs e)
        {
            var paychecks = new PaychecksService.PaychecksServiceClient();

            paychecks.FineSalaryCompleted += (s, ea) =>
            {
                if (ea.Error == null)
                {
                    string resultMessage = ea.Result ? "Salary was fined succesfully" : "Paycheck wasn't approved yet";
                    MessageBox.Show(resultMessage);
                }
                else
                {
                    MessageBox.Show("Failed fine salary: " + ea.Error.Message);
                }
            };

            int fineAmount = 0;
            int.TryParse(this.textBoxFine.Text, out fineAmount);
            if (fineAmount > 0)
            {
                paychecks.FineSalaryAsync(m_searchedUserID, m_selectedMonth, fineAmount);
            }
            else
            {
                MessageBox.Show("Fine Must be integer bigger then 0");
            }
        }
    }
}
